#pragma once
#include<iostream>
namespace H {
	template<class T>
	struct list_node {
		list_node<T>* _next;
		list_node<T>* _prev;
		T _val;
		list_node(const T& val = T())
			:_next(nullptr),
			_prev(nullptr),
			_val(val)
		{

		}
	};

	template<class T, class Ref, class Ptr>
	struct list_iterator {
		typedef list_node<T> Node;
		typedef list_iterator<T, Ref, Ptr> self;
		Node* _node;
		list_iterator(Node* node)
			:_node(node)
		{

		}
		Ref operator *()
		{
			return _node->_val;
		}
		Ptr operator->()
		{
			return &_node->_val;
		}
		self& operator++()
		{
			_node = _node->_next;
			return *this;
		}
		self operator++(int)
		{
			self tmp(*this);
			_node = _node->_next;
			return tmp;
		}
		self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}
		self operator--(int)
		{
			self tmp(*this);
			_node = _node->_prev;
			return tmp;
		}
		bool operator!=(const self& it)const
		{
			return _node != it._node;
		}
		bool operator==(const self& it)const
		{
			return _node == it._node;
		}

	};


	template<class T>
	class list {
		typedef list_node<T> Node;
	public:
		typedef list_iterator<T, T&, T*>iterator;
		typedef list_iterator<T, const T&, const T*>const_iterator;

		list()
		{
			empty_init();
		}
		list(const list<T>& lt)
		{
			empty_init();

			for (auto& e : lt)
			{
				push_back(e);
			}
		}
		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}
		iterator begin()
		{
			return _head->_next;
		}
		iterator end()
		{
			return _head;
		}
		const_iterator begin()const
		{
			return _head->_next;
		}
		const_iterator end()const
		{
			return _head;
		}
		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
			_size = 0;
		}

		void push_back(const T& x)
		{
			insert(end(), x);
		}

		void push_front(const T& x)
		{
			insert(begin(), x);
		}

		void pop_back()
		{
			erase(--end());
		}

		void pop_front()
		{
			erase(begin());
		}

		void swap(list<T>& l)
		{
			std::swap(_head, l._head);
			std::swap(_size, l._size);
		}
		list<T>& operator=(list<T> lt)
		{
			swap(lt);
			return *this;
		}
		void clear()
		{
			iterator it = begin();
			while (it != end())
			{
				it = erase(it);
			}

			_size = 0;
		}
		iterator insert(iterator pos, const T& x)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;
			Node* newnode = new Node(x);

			prev->_next = newnode;
			newnode->_prev = prev;

			newnode->_next = cur;
			cur->_prev = newnode;
			_size++;
			return newnode;
		}
		iterator erase(iterator pos)
		{
			Node* cur = pos._node;
			Node* prev = cur->_prev;

			prev->_next = cur->_next;
			cur->_next->_prev = prev;
			delete cur;
			_size--;
			return prev->_next;
		}
		size_t size()
		{
			return _size;
		}
	private:
		Node* _head;
		size_t _size;
	};
}
